<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'shop:order:soMain:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="70%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #remarks="{ model, field }">
        <WangEditor
          v-model:value="model[field]"
          :bizKey="record.id"
          :bizType="'testDataChild_' + field"
          :height="300"
        />
      </template>
      <template #testDataChildList>
        <!--  @row-click="handleTestDataChildRowClick" -->
        <BasicTable @register="registerTestDataChildTable"> </BasicTable>
        <!-- <a-button class="mt-2" @click="handleTestDataChildAdd" v-auth="'shop:order:soMain:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsShopOrderSubmitForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { saveBackOrder } from '/@/api/shop/order/soMain';
  import { officeTreeData } from '/@/api/sys/office';
  import { areaTreeData } from '/@/api/sys/area';
  import { BasicUpload } from '/@/components/Upload';
  import { WangEditor } from '/@/components/WangEditor';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('shop:order:soMain');
  const { showMessage } = useMessage();
  const record = ref<any>({} as any);
  const getTitle = computed(() => ({
    icon: 'simple-line-icons:basket-loaded',
    value: t('提交订单'),
  }));

  // const inputFormSchemas: FormSchema[]=[]

  const [registerForm, { resetFields, setFieldsValue, getFieldsValue, validate, setProps }] =
    useForm();

  const [registerTestDataChildTable, testDataChildTable] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record: Recordable) => [
    //     {
    //       icon: 'ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handleTestDataChildDelete.bind(this, record),
    //       },
    //       auth: 'shop:order:soMain:edit',
    //     },
    //   ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setTestDataChildTableData(_res: Recordable) {
    testDataChildTable.setColumns([
      {
        title: t('存货编码'),
        dataIndex: 'cinvcode',
        width: 130,
        align: 'left',
      },
      {
        title: t('存货名称'),
        dataIndex: 'cinvname',
        width: 240,
        align: 'left',
      },
      // {
      //   title: t('协同路线'),
      //   dataIndex: 'croute',
      //   width: 150,
      //   align: 'left',
      // },
      // {
      //   title: t('规格型号'),
      //   dataIndex: 'cinvstd',
      //   width: 130,
      //   align: 'left',

      // },
      // {
      //   title: t('分类代码'),
      //    dataIndex: 'invCls.name',
      //   width: 130,
      //   align: 'left',

      // },
      {
        title: t('单位'),
        dataIndex: 'unitName',
        width: 80,
        align: 'center',
      },
      {
        title: t('税率'),
        dataIndex: 'itaxrate',
        width: 80,
        align: 'center',
      },
      // {
      //   title: t('参考售价'),
      //    dataIndex: 'iinvscost',
      //   width: 130,
      //   align: 'left',
      // },
      // {
      //   title: t('最低售价'),
      //   dataIndex: 'iinvlscost',
      //   align: 'left',
      //   width: 100,
      // },
      // {
      //   title: t('零售单价'),
      //   dataIndex: 'iinvsalecost',
      //   align: 'left',
      //   width: 100,
      // },
      {
        title: t('零售价格'),
        dataIndex: 'fretailprice',
        align: 'center',
        width: 80,
      },
      {
        title: t('数量'),
        dataIndex: 'inum',
        width: 80,
        align: 'center',
        // editable: true,
        // // edit: true,
        // editRow: true,
        // editComponent: 'InputNumber',
        // editRule: true,
      },
    ]);
    // testDataChildTable.setTableData(record.value.testDataChildList || []);
    testDataChildTable.setTableData(record.value.rdsList || []);
  }

  function handleTestDataChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleTestDataChildAdd() {
    testDataChildTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleTestDataChildDelete(record: Recordable) {
    testDataChildTable.deleteTableDataRecord(record);
  }

  async function getTestDataChildList() {
    let testDataChildListValid = true;
    let testDataChildList: Recordable[] = [];

    for (const record of testDataChildTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        testDataChildListValid = false;
      }
      testDataChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    // for (const record of testDataChildTable.getDelDataSource()) {
    //   if (!!record.isNewRecord) continue;
    //   testDataChildList.push({
    //     ...record,
    //     status: '1',
    //   });
    // }
    if (!testDataChildListValid) {
      throw { errorFields: [{ name: ['testDataChildList'] }] };
    }
    return testDataChildList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    // const res = await testDataForm(data);
    record.value = data;
    record.value.__t = new Date().getTime();
    record.value.isNewRecord = false;
    let inputFormSchemas: FormSchema[] = [
      {
        label: t('客户编码'),
        field: 'cusCode',
        dynamicDisabled: true,
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
        required: true,
      },
      {
        label: t('客户名称'),
        field: 'cusName',
        dynamicDisabled: true,
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
        required: true,
      },
      {
        label: t('商品'),
        field: 'testDataChildList',
        component: 'Input',
        colProps: { lg: 24, md: 24 },
        slot: 'testDataChildList',
      },
      {
        label: t('优惠金额'),
        field: 'disMoney',
        dynamicDisabled: true,
        defaultValue:'0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },
      {
        label: t('商品总价'),
        field: 'sumMoney',
        dynamicDisabled: true,
        defaultValue:'0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },

      {
        label: t('经销商余额'),
        field: 'cusMoney.appZhMoney',
        dynamicDisabled: true,
        defaultValue:'0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },
      {
        label: t('合计金额'),
        field: 'payMoney',
        dynamicDisabled: true,
        defaultValue:'0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },

      {
        label: t('经销商返利余额'),
        field: 'cusMoney.appFlMoney',
        dynamicDisabled: true,
        defaultValue:'0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },
      {
        label: t('经销商促销余额'),
        field: 'cusMoney.appCxMoney',
        dynamicDisabled: true,
        defaultValue:'0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },
      {
        label: t('返利金额上限'),
        field: 'flMoneyLmit',
        dynamicDisabled: true,
        defaultValue:'0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },
      {
        label: t('促销金额上限'),
        field: 'cxMoneyLmit',
        dynamicDisabled: true,
        defaultValue:'0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },

      {
        label: t('使用返利余额'),
        field: 'flMoney',
        component: 'Input',
        componentProps: {
          maxlength: 200,
          onChange(e) {
            console.log(e);
          },
        },
        colProps: { lg: 12, md: 24 },
      },
      {
        label: t('使用促销余额'),
        field: 'cxMoney',
        component: 'Input',
        componentProps: {
          maxlength: 200,
          onChange(e) {
            console.log(e);
          },
        },
        colProps: { lg: 12, md: 24 },
      },
      {
        label: t('核发门店'),
        field: 'hfmdCode',
        component: 'ListSelect',
        componentProps: {
          selectType: 'basPersonSelect',
        },
      },
      {
        label: t('备注'),
        field: 'remarks',
        component: 'InputTextArea',
        componentProps: {
          maxlength: 200,
        },
      },
    ];
    await setProps({
      labelWidth: 120,
      schemas: inputFormSchemas,
      baseColProps: { lg: 24, md: 24 },
    });
    console.log(record.value);

    setFieldsValue(record.value);
    // setTestDataChildTableData();
    setTimeout(() => {
      setTestDataChildTableData(record.value);
    }, 500);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();

      // setDrawerProps({ confirmLoading: true });
      const params: any = {
        // isNewRecord: record.value.isNewRecord,
        // id: record.value.id,
      };
      data.rdsList = await getTestDataChildList();

      console.log('submit', params, data, record);
      const res = await saveBackOrder(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }
  /* .jeesite-editable-cell__action {
    display: none;
  } */

  :deep(.edit-cell-align-center) {
    width: 100% !important;
  }
</style>
